/*
	by Ilija
*/


#include "mygl_ext.h"


void glEnableTexture(const GLTexture* tex)
{
	if (tex)
	{
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, tex->getTextureId());
	}
}

void glDisableTexture()
{
	glDisable(GL_TEXTURE_2D);
}


void glDrawImage(const GLTexture* texture, const rectf& destRect, const Color& color)
{
	if (!texture)
		return;
	glPushAttrib(GL_CURRENT_BIT);
	glColor(color);
	glEnableTexture(texture);
	glBegin(GL_QUADS);
		glTexCoord2f(0.0f, 0.0f);
		glVertex2f(destRect.AA.x, destRect.BB.y);
		glTexCoord2f(1.0f, 0.0f);
		glVertex2f(destRect.BB.x, destRect.BB.y);
		glTexCoord2f(1.0f, 1.0f);
		glVertex2f(destRect.BB.x, destRect.AA.y);
		glTexCoord2f(0.0f, 1.0f);
		glVertex2f(destRect.AA.x, destRect.AA.y);
	glEnd();
	glDisableTexture();
	glPopAttrib();
}


void glDrawText(const GLFont* fnt, float x, float y, const String& str, const Color& c)
{
	if (!fnt)
		return;
	fnt->drawText(x, y, str, c);
}

void glRenderImage(const GLTexture* tex, const rectf& dst, const rectf& src)
{
    if (!tex)
        return;

    float x1 = dst.AA.x;
    float y1 = dst.AA.y;
    float x2 = dst.BB.x;
    float y2 = dst.BB.y;

    float u1 = src.AA.x;
    float v1 = src.AA.y;
    float u2 = src.BB.x;
    float v2 = src.BB.y;

    tex->enable();
    glBegin(GL_QUADS);
        //normal
        glNormal3f(0.0f, 0.0f, 1.0f);
        //verteces
        glTexCoord2f(u1, v1);
        glVertex2f(x1, y1);
        glTexCoord2f(u2, v1);
        glVertex2f(x2, y1);
        glTexCoord2f(u2, v2);
        glVertex2f(x2, y2);
        glTexCoord2f(u1, v2);
        glVertex2f(x1, y2);
    glEnd();
    tex->disable();
}

void glRenderSprite(const GLTexture* tex, float w, float h,
                    bool has_alpha,
                    bool back_cull,
                    bool depth_test)
{
    if (!tex)
        return;

    float x1 = -w/2;
    float y1 = -h/2;
    float x2 = w/2;
    float y2 = h/2;

    tex->enable();
    glPushAttrib(GL_ENABLE_BIT);
    if (has_alpha) glEnable(GL_ALPHA_TEST);
    if (!back_cull) glDisable(GL_CULL_FACE);
    if (!depth_test) glDisable(GL_DEPTH_TEST);
    glBegin(GL_QUADS);
        //normal
        glNormal3f(0.0f, 0.0f, 1.0f);
        //verteces
        glTexCoord2f(0.0f, 0.0f);
        glVertex2f(x1, y1);
        glTexCoord2f(1.0f, 0.0f);
        glVertex2f(x2, y1);
        glTexCoord2f(1.0f, 1.0f);
        glVertex2f(x2, y2);
        glTexCoord2f(0.0f, 1.0f);
        glVertex2f(x1, y2);
    glEnd();
    glPopAttrib();
    tex->disable();
}

